from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QMenu
import os
from PyQt5.QtCore import QThread
from snmpProcess import *

DEVICE_WATCHING_FILE_PATH = './DeviceWatching.txt'

class DataLoaderThread(QThread):
    def __init__(self, parent):
        super().__init__()
        self.p = parent

    def run(self):
        self.p.updateData()

class DeviceDetail(QTableWidget):
    def __init__(self):
        super().__init__()
        self.setColumnCount(4)
        self.setHorizontalHeaderLabels(['设备IP', '读团体码', '写团体码', 'UpTime'])
        self.OIDs = ['1.3.6.1.2.1.1.3.0']
        self.base_inf = []
        kept = self.readDeviceWatching()
        for i in kept:
            self.addBaseData(i)
        # 创建并启动数据加载线程
        self.data_loader_thread = DataLoaderThread(self)
        
    def contextMenuEvent(self, event):
        context_menu = QMenu(self)
        delete_action = context_menu.addAction('删除监视')

        action = context_menu.exec_(self.mapToGlobal(event.pos()))

        if action == delete_action:
            self.deleteSelectedRow()
            
    def deleteSelectedRow(self):
        selected_row = self.currentRow()
        if selected_row != -1:
            self.removeRow(selected_row)
            self.base_inf.pop(selected_row)
            self.writeDeviceWatching()

    def addBaseData(self, data: list):
        self.base_inf.append(data)
        row_position = self.rowCount()
        self.insertRow(row_position)
        for col, value in enumerate(data):
            item = QTableWidgetItem(value)
            self.setItem(row_position, col, item)
            
    def readDeviceWatching(self, device_watching_file_path=DEVICE_WATCHING_FILE_PATH):
        """
        读取监视文件
        """
        device_watching = []
        if os.path.exists(device_watching_file_path):
            with open(device_watching_file_path, 'r') as f:
                while True:
                    rl = f.readline()
                    if not rl:
                        break
                    device_watching.append(rl.strip().split(' '))
        return device_watching
    
    def writeDeviceWatching(self, device_watching_file_path=DEVICE_WATCHING_FILE_PATH):
        """
        重写监视文件
        """
        with open(device_watching_file_path, 'w') as f:
            for item in self.base_inf:
                f.write(' '.join(i for i in item) + '\n')
    
    def addWatch(self, ip, com_read, com_write):
        """
        添加监视
        """
        if not any(ip == row[0] for row in self.base_inf):
            self.addBaseData([ip, com_read, com_write])
            self.writeDeviceWatching()
        
    def updateData(self):
        """
        更新数据
        """
        for i, base_inf_i in enumerate(self.base_inf):
            for ii, OID_i in enumerate(self.OIDs):
                # 启动数据加载线程
                val = resultOnly(SnmpProcess(base_inf_i[0], base_inf_i[1], base_inf_i[2]).commandParserGet(OID_i))
                it = QTableWidgetItem(val)
                self.setItem(i, ii + 3, it)
                
    # def updateData(self):
    #     for i, base_inf_i in enumerate(self.base_inf):
    #         for ii, OID_i in enumerate(self.OIDs):
    #             # 创建并启动更新数据线程
    #             update_thread = UpdateDataThread(base_inf_i, OID_i, i, ii)
    #             update_thread.update_finished.connect(self.handleUpdateResult)
    #             update_thread.start()

    # def handleUpdateResult(self, result):
    #     """
    #     处理更新数据线程的结果
    #     """
    #     val, i, ii = result
    #     for i, base_inf_i in enumerate(self.base_inf):
    #         if base_inf_i == base_inf:
    #             it = QTableWidgetItem(val)
    #             self.setItem(i, ii + 3, it)